<?php
/**
 * User: Drery
 * Date: 2015/11/16
 * Time: 18:39
 */

namespace api\behaviors;
use api\components\AppException;
use Yii;
use yii\filters\auth\AuthMethod;
use yii\web\UnauthorizedHttpException;

class Auth extends AuthMethod{
    /**
     * @param \yii\web\User $user
     * @param \yii\web\Request $request
     * @param \yii\web\Response $response
     * @return null|\yii\web\IdentityInterface
     */
    public function authenticate($user, $request, $response)
    {
        $method = strtolower(Yii::$app->request->method);
        $accessToken = $request->$method('access_token');
        if ($accessToken && is_string($accessToken)) {
            $identity = $user->loginByAccessToken($accessToken, get_class($this));
            if ($identity !== null) {
                if ($identity->is_forbidden || $identity->is_deleted) {
                    throw new AppException(AppException::ERROR_USER_FORBIDDEN);
                }
                if (!$identity->vehicle) {
                    throw new AppException(AppException::ERROR_USER_ABNOMAL);
                }
                Yii::$app->user->setIdentity($identity);
                return $identity;
            }
        }
        return null;
    }

    /**
     * @param \yii\base\Action $action
     * @return bool
     */
    protected function isActive($action)
    {
        $action_id = $action->id;
        $controller_id = $action->controller->id;
        $id = $controller_id.'/'.$action_id;
        return !in_array($id, $this->except, true) && (empty($this->only) || in_array($id, $this->only, true));
    }

    public function handleFailure($response)
    {
        throw new UnauthorizedHttpException;
    }
}